import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Modal,
  Space
} from 'ant-design-vue'
import { title } from 'process'
import { defineComponent, ref } from 'vue'

import { cinemaApi, marketingApi } from '@/apis'
import { RulesListItem } from '@/apis/marketingTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import UploadFile from '@/components/UploadFile'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useBack, useDialog } from '@/hooks'

export default defineComponent({
  name: 'Reservation',
  setup() {
    const isAddStyle = ref(true)
    const liveBookingTitle = ref('')
    const dataList = ref([] as any)
    const datas = ref([] as any)
    const { handleCancel } = useBack('refreshCouponManage')
    const liveTitle = ref([] as any)
    const curOptionItem = ref({} as RulesListItem)
    const confirmLoading = ref(false)
    const showDialog = ref(false)
    const dialogLoading = ref(false)
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'addStyle'
          }
        },
        formConfig: {
          items: [
            {
              title: '预约攻略标题：',
              field: 'liveBookingTitle',
              slots: {
                default: 'InputButtons'
              }
            }
          ]
        },
        columns: [
          {
            title: '序号',
            field: 'sort',
            width: '180'
          },
          {
            title: 'Banner',
            field: 'bannerImg',
            slots: {
              default: 'bannerImage'
            }
          },
          {
            title: '操作',
            fixed: 'right',
            width: '200',
            slots: {
              default: 'operation'
            }
          }
        ],

        proxyConfig: {
          props: {
            result: 'data'
          },
          ajax: {
            query: async () => {
              const data = await marketingApi.getRulesList()
              liveTitle.value = data.liveBookingTitle
              const arr: any = []
              if (isAddStyle.value) {
                if (dataList.value.length != 0) {
                  dataList.value.map(k =>
                    arr.push({ bannerImg: k.bannerImg, sort: k.sort })
                  )
                  arr.map(k => data.bannerList.push(k))
                }
                datas.value = [...data.bannerList]
              } else {
                data.bannerList = [...datas.value]
              }
              return data.bannerList
            }
          }
        }
      }
    } as ProTableProps)

    //刷新
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }

    // 保存
    async function handleSave(flag) {
      try {
        confirmLoading.value = true
        await marketingApi
          .editBannerTemplete({
            bannerList: datas.value,
            liveBookingTitle: liveTitle.value
          })
          .then(() => {
            message.success('保存成功')
            refresh()
          })
      } finally {
        confirmLoading.value = false
        isAddStyle.value = false
      }
    }
    const rowItem = ref([] as any)
    //编辑
    function handleEdit(item: RulesListItem) {
      curOptionItem.value.bannerImg = item.bannerImg
      curOptionItem.value.sort = item.sort

      isAddStyle.value = false
      showDialog.value = true
      rowItem.value = item
    }
    //标题
    function handleReservation(item) {
      curOptionItem.value.liveBookingTitle = item.liveBookingTitle
    }
    // 新增
    function handleAdd() {
      curOptionItem.value.bannerImg = ''
      curOptionItem.value.sort = 1
      isAddStyle.value = true
      showDialog.value = true
    }
    //确定
    function dialogConfirm() {
      if (!curOptionItem.value.bannerImg) {
        message.warn('请添加Banner图片')
        return
      }
      if (!curOptionItem.value.sort) {
        message.warn('请添加Banner图排序')
        return
      }
      if (isAddStyle.value) {
        dataList.value.push({
          bannerImg: curOptionItem.value.bannerImg,
          sort: curOptionItem.value.sort
        })
        refresh()
      } else {
        datas.value.map(item => {
          if (item._X_ROW_KEY == rowItem.value._X_ROW_KEY) {
            item.bannerImg = curOptionItem.value.bannerImg
            item.sort = curOptionItem.value.sort
          }
        })
        refresh()
      }
      showDialog.value = false
    }

    //删除
    function handleDelete(row) {
      rowItem.value = row
      isAddStyle.value = false
      showConfirm({
        content: '确认删除？',
        onOk: () => {
          datas.value.map((item, index) => {
            if (item._X_ROW_KEY == rowItem.value._X_ROW_KEY) {
              datas.value.splice(index, 1)
            }
          })
          handleSave(row)
          // try {
          //   await marketingApi.editBannerTemplete({
          //     bannerList: datas.value,
          //     liveBookingTitle: liveBookingTitle.value
          //   })
          //   console.log(datas.value, '===================')
          // } finally {
          //   isAddStyle.value = false
          // }
          // datas.value.map((item, index) => {
          //   if (item._X_ROW_KEY == rowItem.value._X_ROW_KEY) {
          //     datas.value.splice(index, 1)
          //   }
          // })
          refresh()
        }
      })
      showDialog.value = false
    }

    return {
      liveTitle,
      tableRef,
      tableConfig,
      curOptionItem,
      showDialog,
      dialogLoading,
      confirmLoading,
      liveBookingTitle,
      isAddStyle,
      handleCancel,
      handleSave,
      dialogConfirm,
      handleReservation,
      handleEdit,
      handleAdd,
      handleDelete
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          style={{
            width: '1000px'
          }}
          v-slots={{
            bannerImage: ({ row }) => (
              <Image
                // style={{ width: '180px', height: '180px' }}
                src={row.bannerImg}
              ></Image>
            ),
            InputButtons: row => {
              return (
                <FormItem
                  style={{
                    marginTop: '26px'
                  }}
                >
                  <Input
                    onClick={() => this.handleReservation(row)}
                    placeholder={'请输入预约攻略标题'}
                    v-model:value={this.liveTitle}
                    style={{ width: '300px' }}
                    maxlength={20}
                  />
                  <span
                    style={{
                      marginLeft: '10px',
                      color: 'grey'
                    }}
                  >
                    最多输入20个字
                  </span>
                </FormItem>
              )
            },
            addStyle: row => {
              return (
                <Space>
                  <span>预约攻略Banner:</span>
                  <Button
                    style={{
                      marginLeft: '10px'
                    }}
                    type="primary"
                    // onClick={this.handleAdd}
                    onClick={this.handleAdd}
                  >
                    新增
                  </Button>
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          width={600}
          title={this.isAddStyle ? '新增' : '编辑'}
          destroyOnClose
          onOk={() => this.dialogConfirm()}
        >
          <Form labelCol={{ span: 4 }} style={{ marginTop: '15px' }}>
            <FormItem label={'上传图片'} required>
              <UploadFile v-model={[this.curOptionItem.bannerImg, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'排序'} required>
              <InputNumber
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.sort}
                style={{ width: '300px' }}
                min={1}
                maxlength={4}
              />
            </FormItem>
          </Form>
        </Modal>
        <FormItem colon={false} wrapperCol={{ span: 24 }}>
          <Button
            loading={this.confirmLoading}
            type="primary"
            onClick={() => this.handleSave('save')}
            style={{
              width: '200px',
              height: '40px',
              marginTop: '10px',
              marginBottom: '10px'
            }}
          >
            保存
          </Button>
          <Button
            loading={this.confirmLoading}
            onClick={this.handleCancel}
            style={{
              width: '200px',
              height: '40px',
              marginTop: '30px',
              marginBottom: '10px',
              marginLeft: '50px'
            }}
          >
            取消
          </Button>
        </FormItem>
      </div>
    )
  }
})
